<template>
  <div>
    <el-dialog
      :title="title"
      :close-on-click-modal="false"
      v-dialogDrag
      :visible.sync="visible"
    >
      <fm-generate-form
        v-if="visible && show"
        :edit="method !== 'view'"
        :data="options"
        :value="initData"
        :class="method === 'view' ? 'readonly' : ''"
        ref="generateForm"
      >
      </fm-generate-form>
      <span slot="footer" class="dialog-footer">
        <el-button
          size="small"
          @click="
            () => {
              this.show = false;
              this.visible = false;
              this.formId = '';
            }
          "
          >关闭</el-button
        >
        <el-button
          size="small"
          type="primary"
          v-if="method != 'view'"
          @click="doSubmit()"
          >确定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      title: "",
      show: false,
      method: "",
      formId: "",
      beanId: "",
      visible: false,
      initData: {},
      dataBindMap: new Map(),
      options: { list: [] },
    };
  },
  watch: {
    formId(newFormId, oldFormId) {
      if (newFormId !== oldFormId) {
        // 监听到组件传入的formId变化时，重新获取表单数据
        this.createForm();
      }
    },
  },
  created() {},
  mounted() {
    // this.createForm();
  },
  components: {},
  methods: {
    async init(method, formId, beanId) {
      this.method = method;
      this.beanId = beanId;
      this.formId = formId;
      this.initData = {};
      if (method === "add") {
        this.title = `新建`;
      } else if (method === "edit") {
        this.title = "修改";
      } else if (method === "view") {
        this.title = "查看";
      }
      this.visible = true;
      this.loading = false;
      this.$nextTick(() => {
        // this.$refs.generateForm.reset();
        if (beanId) {
          this.loading = true;
          this.$http({
            url: `/form/generate/queryById?formId=${formId}&id=${beanId}`,
            method: "get",
          }).then(({ data }) => {
            this.loading = false;
            for (let key in data.data.obj) {
              let dataField = this.dataBindMap.get(key);
              if (
                dataField &&
                (dataField["type"] === "checkbox" ||
                  dataField["type"] === "imgupload" ||
                  dataField["type"] === "table" ||
                  (dataField["type"] === "select" &&
                    dataField.options.multiple) ||
                  dataField["type"] === "fileupload")
              ) {
                if (
                  data.data.obj[key] &&
                  typeof data.data.obj[key] === "string"
                ) {
                  data.data.obj[key] = JSON.parse(data.data.obj[key]);
                } else if (!data.data.obj[key]) {
                  data.data.obj[key] = [];
                }
              }

              if (
                dataField &&
                (dataField["type"] === "number" ||
                  dataField["options"].dataType === "number")
              ) {
                if (
                  data.data.obj[key] !== undefined &&
                  data.data.obj[key] !== "" &&
                  typeof data.data.obj[key] === "string"
                ) {
                  data.data.obj[key] = JSON.parse(data.data.obj[key]);
                }
              }
            }
            this.initData = data.data.obj;
            this.show = true;
          });
        }
      });
    },
    generateModel(genList) {
      for (let i = 0; i < genList.length; i++) {
        if (genList[i].type === "grid") {
          genList[i].columns.forEach((item) => {
            this.generateModel(item.list);
          });
        } else if (genList[i].type === "tabs") {
          genList[i].tabs.forEach((item) => {
            this.generateModel(item.list);
          });
        } else {
          // 处理老版本没有dataBind值的情况，默认绑定数据
          if (genList[i].options.dataBind) {
            this.dataBindMap.set(genList[i].model, genList[i]);
          }
        }
      }
    },
    createForm() {
      this.$http({
        url: `/form/make/queryById?id=${this.$route.query.id}`,
      }).then(({ data }) => {
        if (data.data.form.source) {
          this.options = JSON.parse(data.data.form.source);
        } else {
          this.options = {
            list: [],
            config: {
              labelWidth: 100,
              labelPosition: "right",
              size: "small",
              customClass: "",
            },
          };
        }
        this.dataBindMap.clear();
        this.generateModel(this.options.list);
        this.show = true;
      });
    },

    // 表单提交
    doSubmit() {
      // 自定义js ，保存前执行
      if (this.options.config.eventType === "1") {
        // eslint-disable-next-line no-new-func
        new Function(`return ${this.options.config.customJs}`)();
      }
      this.$refs.generateForm
        .getData()
        .then((data) => {
          if (this.beanId) {
            data.id = this.beanId;
          }
          this.$http({
            url: `/form/generate/save`,
            method: "post",
            data: { formId: this.$route.query.id, data: JSON.stringify(data) },
          }).then(({ data }) => {
            if (data.code == 0) {
              this.visible = false;
              this.show = false;
              this.formId = "";
              this.$message.success(data.info);
              this.$emit("refreshDataList");
            }
            // 自定义js 保存后执行
            if (this.options.config.eventType === "2") {
              // eslint-disable-next-line no-new-func
              new Function(`return ${this.options.config.customJs}`)();
            }
          });
        })
        .catch((e) => {});
    },
  },
};
</script>
